#!/usr/bin/env python
#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.

import log_parser
import vuze_util

import itertools
import optparse
import sys
import time

def scan_logs(logs, no_peer_records=False, no_torrent_descs=False):
  for log in logs:
    print log
    res = log_parser.get_stores(log)
    if no_peer_records:
      def prec_filter(x):
        x = x[3]
        return ((x and len(x) <= 5 and x.isdigit) or vuze_util.is_peer_record(x))
      res = itertools.ifilterfalse(prec_filter, res)
    if no_torrent_descs:
      def tdesc_filter(x):
        x = x[3]
        return (vuze_util.is_torrent_description(x[3]) or
                (x[3][0] == '\x00' and vuze_util.is_torrent_description(x[3][1:])))
      res = itertools.ifilterfalse(lambda x: vuze_util.is_torrent_description(x[3]), res)
    for (key, store_time, version, value) in res:
      print '\nKey:', ''.join((hex(ord(c))[2:].upper()) for c in key)
      print 'Time:', time.ctime(store_time)
      print 'Value:', repr(value)

def main(argv):
  parser = optparse.OptionParser()
  parser.add_option('--no-peers', action='store_true', dest='no_peers',
                    default=False)
  parser.add_option('--no-torrent-descs', action='store_true',
                    dest='no_torrent_descs', default=False)
  options, args = parser.parse_args(argv[1:])
  print options.no_peers
  scan_logs(args, options.no_peers, options.no_torrent_descs)

if __name__ == '__main__':
  main(sys.argv)
